/**
 * Created by Administrator on 2017/3/10.
 */
import React from 'react';
import "./examAdd.css"


class ExamEdit extends React.Component{
    componentDidMount(){

        //解析缓存中json
        function parseJson(){
            //回写试卷信息
            var exaMsg = sessionStorage.getItem("exaMsg");
            if(exaMsg!=null && exaMsg.length>0){
                exaMsg = $.parseJSON(exaMsg);
                $(".pName input").val(exaMsg.pName);
                $(".pIntroduce textarea").val(exaMsg.pIntroduce);
                $(".pMark input").val(exaMsg.pMark);
                $(".selectType").find("option[value="+exaMsg.select+"]").prop("selected",true);
            }

            //回写静态题目
            var pHtml = sessionStorage.getItem("pHtml");
            if(pHtml!=null && pHtml.length>0) {
                $(".N_question").html(pHtml);
                $(".hint").prop("hidden",true);

                //回写题目分数
                var allScore = sessionStorage.getItem("allScore");
                var allScoreArr = allScore.split(',');
                $(".N_mark").each(function (index) {
                    $(this).val(allScoreArr[index]);
                });
                var partScore = sessionStorage.getItem("partScore");
                var partScoreArr = partScore.split(',');
                $(".N_parkMark").each(function (index) {
                    $(this).val(partScoreArr[index]);
                });
            }

            // 解析题目json
            var pJson = sessionStorage.getItem("pJson");
            if(isJSON(pJson)&&pJson != null && pJson.length > 0 ){
                var obj = $.parseJSON(pJson);
                var problems = "";
                for(var i=0;i < obj.length;i++){
                    var eIndex = i+1;
                    var num = $(".N_question").find("dl").length;
                    console.log(num);
                    problems += '<dl hidden="false"><dt><input type="checkbox"  class="N_oneChose"><input name="eProblemsQuery['+i+'].eIndex" value="'+eIndex+'" class="N_questionNum" readOnly="true"/>'
                    problems += '<input type="hidden" name="eProblemsQuery['+i+'].notes" value="'+obj[i].notes+'">';
                    problems += '<input type="hidden" name="eProblemsQuery['+i+'].result" value="'+obj[i].result+'">';
                    problems += '<input hidden="true" name="eProblemsQuery['+i+'].problemsId" value="'+obj[i].id+'" >';
                    switch(Number(obj[i].problemType))
                    {
                        case 0:
                            problems += '<input type="hidden" name="eProblemsQuery['+i+'].problemType" value="0"><b class="N_type" value="0">单选题</b>';
                            break;
                        case 1:
                            problems += '<input type="hidden" name="eProblemsQuery['+i+'].problemType" value="1"><b class="N_type" value="1">多选题</b>';
                            break;
                        case 2:
                            problems += '<input type="hidden" name="eProblemsQuery['+i+'].problemType" value="2"><b class="N_type" value="2">判断题</b>';
                            break;
                        default:
                            problems += '<input type="hidden" name="eProblemsQuery['+i+'].problemType" value="null"><b class="N_type" value="null"></b>';
                    }
                    switch(Number(obj[i].difficulty))
                    {
                        case 0:
                            problems += '<input type="hidden" name="eProblemsQuery['+i+'].difficulty" value="0"><b class="N_difficulty">易</b>';
                            break;
                        case 1:
                            problems += '<input type="hidden" name="eProblemsQuery['+i+'].difficulty" value="1"><b class="N_difficulty">中</b>';
                            break;
                        case 2:
                            problems += '<input type="hidden" name="eProblemsQuery['+i+'].difficulty" value="2"><b class="N_difficulty">难 </b>';
                            break;
                        default:
                            problems += '<input type="hidden" name="eProblemsQuery['+i+'].difficulty" value="null"><b class="N_difficulty"> </b>';
                    }
                    problems += '<input type="hidden" name="eProblemsQuery['+i+'].errorRate" value="'+obj[i].errorRate+'"/><b class="N_accuracy">'+obj[i].errorRate+'</b>';
                    problems += '<input type="hidden" name="eProblemsQuery['+i+'].createDate" value="'+obj[i].createDate+'"/>';
                    problems += '<input type="hidden" name="eProblemsQuery['+i+'].updateDate" value="'+obj[i].updateDate+'"/>';
                    if (obj[i].updateDate == undefined){
                        problems += '<b class="N_time">'+obj[i].createDate+'</b>';
                    }else{
                        problems += '<b class="N_time">'+obj[i].updateDate+'</b>';
                    }
                    problems += '<strong class="N_open">展开</strong>';
                    if(obj[i].problemType==1){
                        problems += '<input type="checkbox" class="onePartScoreChose">部分对得分<input type="text" disabled="disabled" class="N_parkMark" name="eProblemsQuery['+i+'].partScore" >分';
                    }
                    problems += '<div class="N_gaibian">分值：<input type="text" name="eProblemsQuery['+i+'].allScore" value="" class="N_mark">分 <em class="N_up"></em><em class="N_down"></em><em class="N_editor"></em><em class="N_delete"></em></div>';
                    problems += '</dt>';

                    problems += '<input type="hidden" name="eProblemsQuery['+i+'].contents" value="'+obj[i].contents+'"/><dd>'+obj[i].contents+'</dd>';
                    problems += '<input type="hidden" name="eProblemsQuery['+i+'].itemJsonV" value="" />';
                    debugger;
                    if(obj[i].itemJson==='[]'){
                        //result.data.list[index].itemJson="";
                    }else if(!obj[i].itemJson){
                        //result.data.list[index].itemJson="";
                    }else if( !isJSON(obj[i].itemJson)){
                        // var optionList = obj[i].itemJson;
                    }else{
                        var optionList = JSON.parse(obj[i].itemJson);
                        for(var j=0; j<optionList.length;j++){
                            var str = optionList[j].numberIndex+"."+optionList[j].content;
                            var str2 = JSON.stringify(optionList[j]);
                            problems += '<dd class="N_item">'+str+'</dd>';}
                    }
                    problems += '</dl>';
                }
                $(".hint").prop("hidden",true);
                $(".N_question").append(problems);
                for(var i=0;i < obj.length;i++) {
                    $('input[name="eProblemsQuery['+i+'].itemJsonV"]').val(obj[i].itemJson);
                }
            }
        }
        //选择题型
        function selectType(){
            var option=$(".selectType option:selected").val(); //选择框的题型值

            var type = $(".N_question").find(".N_type");
            type.each(function(){
                var val = $(this).attr("value");	//题目的题型值
                switch(parseInt(option))
                {
                    case 0:
                        if(val != option){
                            $(this).parents("dl").prop("hidden",true);
                        }else{
                            $(this).parents("dl").prop("hidden",false);
                        }
                        break;
                    case 1:
                        if(val != option){
                            $(this).parents("dl").prop("hidden",true);
                        }else{
                            $(this).parents("dl").prop("hidden",false);
                        }
                        break;
                    case 2:
                        if(val != option){
                            $(this).parents("dl").prop("hidden",true);
                        }else{
                            $(this).parents("dl").prop("hidden",false);
                        }
                        break;
                    default:
                        /*
                         console.log($(this).parents("dl"));
                         */
                        $(this).parents("dl").prop("hidden",false);
                }
            });
        };
        //缓存试卷信息
        function setExaMsg(){
            var pName = $(".pName input").val();
            var pIntroduce = $(".pIntroduce textarea").val();
            var pMark = $(".pMark input").val();
            var select=$(".selectType option:selected").val();
            var exaMsg = '{"pName":"'+pName+'","pIntroduce":"'+pIntroduce+'","pMark":"'+pMark+'","select":"'+select+'"}';
            sessionStorage.setItem("exaMsg",exaMsg);    //缓存 名称 简介 及格分数 选择题型
            var allScore = new Array() ;
            $(".N_mark").each(function (index) {
                allScore[index]  = $(this).val();
            });
            sessionStorage.setItem("allScore",allScore);    //缓存全对得分

            var partScore = new Array() ;
            $(".N_parkMark").each(function (index) {
                partScore[index]  = $(this).val();
            });
            sessionStorage.setItem("partScore",partScore);  //缓存部分对得分
        }
        /**判断是否为json数组**/
        function isJSON (str) {
            str = str.replace(/\s/g, '').replace(/\n|\r/, '');
            if (/^\{(.*?)\}$/.test(str))
                return /"(.*?)":(.*?)/g.test(str);
            if (/^\[(.*?)\]$/.test(str)) {
                return str.replace(/^\[/, '')
                    .replace(/\]$/, '')
                    .replace(/},{/g, '}\n{')
                    .split(/\n/)
                    .map(function (s) { return isJSON(s); })
                    .reduce(function (prev, curr) { return !!curr; });
            }
            return false;
        }
        //保存提交
        $(".btn_keep").click(function(){
            $('.examinationName').val($('.V_examinationName').val());
            $('.resourceDesc').val($('.V_resourceDesc').val());
            $('.passScore').val($('.V_passScore').val());
            var pName = $(".pName input").val();
            var pIntroduce = $(".pIntroduce textarea").val();
            var pMark = $(".pMark input").val();

            var url = "http://192.168.2.176:8080/s/resources/hExamination/save";
            var param  =  $('#edit_details').serializeArray();
            JSON.parse(sessionStorage.getItem("pJson"));
            $.post(url,param,function(data){
                if (data.status) {
                    alert(data.message);
                    /*
                     window.location.href="hExaminationController.do?list";
                     */
                }else{
                    alert("操作失败！");
                }
            });

        });

        //添加题目序号
        function addeIndex(){
            $(".N_questionNum").each(function (index) {
                $(this).val(index+1);
            })
        }
        //异步请求（同步）
/*
        let id = $(".examinationId").val();
*/
        let examId =this.props.params.id;
        $.ajax({
            type: "POST",
            url: "http://192.168.2.176:8080/s/resources/hExamination/form",
            data: {'id':examId},
            async:false,
            success: function(data){
                let mExam = data.data;
                $(".V_examinationName").val(mExam.examinationName);
                $(".V_resourceDesc").val(mExam.resourceDesc);
                $(".V_passScore").val(mExam.passScore);
                let pJson = JSON.stringify(mExam.eproblemsQuery);
                sessionStorage.setItem("pJson",pJson);
                parseJson();
                statistics();
                selectType();
            }
        });
        // 题目统计 0 单选 ; 1 多选 ; 2 判断
        function statistics() {
            var typeArr = $(".N_type");
            var markArr = $(".N_mark");
            var contentNum0 = 0;
            var contentNum1 = 0;
            var contentNum2 = 0;
            var contentMark0 = 0;
            var contentMark1 = 0;
            var contentMark2 = 0;
            typeArr.each(function(index) {
                var countI = index;
                var i = $(this);
                markArr.each(function(index) {
                    if (countI == index) {
                        var j = $(this);
                        if (i.attr("value") == 0) {
                            contentNum0++;
                            contentMark0 += parseInt(j.prop("value")) ? parseInt(j
                                    .prop("value")) : 0;
                            return false;
                        }
                        if (i.attr("value") == 1) {
                            contentNum1++;
                            contentMark1 += parseInt(j.prop("value")) ? parseInt(j
                                    .prop("value")) : 0;
                            return false;
                        }
                        if (i.attr("value") == 2) {
                            contentNum2++;
                            contentMark2 += parseInt(j.prop("value")) ? parseInt(j
                                    .prop("value")) : 0;
                            return false;
                        }
                    }
                });

            });
            var numSum = 0;
            numSum = contentNum0 + contentNum1 + contentNum2;
            var markSum = 0;
            markSum = contentMark0 + contentMark1 + contentMark2;
            $(".contentNum0").text(contentNum0);
            $(".contentNum1").text(contentNum1);
            $(".contentNum2").text(contentNum2);
            $(".contentMark0").text(contentMark0);
            $(".contentMark1").text(contentMark1);
            $(".contentMark2").text(contentMark2);
            $(".numSum").text(numSum);
            $(".markSum").text(markSum);
            $(".totalScore").val(markSum);
        }
        /*选择题型的事件*/
        $(function(){
            /*选择题型的事件*/
            $(".selectType").change(function(){
                var option=$(".selectType option:selected").val(); //选择框的题型值
                var type = $(".N_question").find(".N_type");
                type.each(function(){
                    var val = $(this).attr("value");	//题目的题型值
                    switch(parseInt(option))
                    {
                        case 0:
                            $(".hiddenPartScore").prop("hidden",true);
                            if(val != option){
                                $(this).parents("dl").prop("hidden",true);
                            }else{
                                $(this).parents("dl").prop("hidden",false);
                            }
                            break;
                        case 1:
                            $(".hiddenPartScore").prop("hidden",false);
                            if(val != option){
                                $(this).parents("dl").prop("hidden",true);
                            }else{
                                $(this).parents("dl").prop("hidden",false);
                            }
                            break;
                        case 2:
                            $(".hiddenPartScore").prop("hidden",true);
                            if(val != option){
                                $(this).parents("dl").prop("hidden",true);
                            }else{
                                $(this).parents("dl").prop("hidden",false);
                            }
                            break;
                        default:
                            $(".hiddenPartScore").prop("hidden",true);
                            $(this).parents("dl").prop("hidden",false);
                    }
                });
            });
        });
        $(function() {
            parseJson();
            statistics();
            selectType();
            // 类型的展开和收起
            $(".openBtn").click(function() {
                if ($(this).text() == "收起") {
                    $(this).text("展开");
                    $(this).css({
                        "background" : 'url("../images/Nopen.gif") no-repeat right center'
                    });
                    $(this).parent().parent().find(".content").css({
                        "display" : "none"
                    })
                } else {
                    $(this).text("收起");
                    $(this).css({
                        "background" : 'url(../images/Nclose.gif) no-repeat right center'
                    });
                    $(this).parent().parent().find(".content").css({
                        "display" : "block"
                    })
                }
            });
            // 展开选项
            let N_swift = true;
            $(document).bind("click",$(".N_open"),function () {
                if (N_swift) {
                    $(this).text("收起");
                    $(this).css("background",
                        "url(../images/Nclose.gif) no-repeat 56px center ");
                    $(this).parent().parent().find(".N_item").css("display",
                        "block");
                    N_swift = false;
                } else {
                    $(this).text("展开");
                    $(this).css("background",
                        "url(../images/Nopen.gif) no-repeat 56px center ");
                    $(this).parent().parent().find(".N_item").css("display",
                        "none");
                    N_swift = true;
                }
            });

            $(".N_open").click(function() {
                alert("1");
                    // console.log($(this.text()))
                    if (N_swift) {
                        $(this).text("收起");
                        $(this).css("background",
                            "url(../images/Nclose.gif) no-repeat 56px center ");
                        $(this).parent().parent().find(".N_item").css("display",
                            "block");
                        N_swift = false;
                    } else {
                        $(this).text("展开");
                        $(this).css("background",
                            "url(../images/Nopen.gif) no-repeat 56px center ");
                        $(this).parent().parent().find(".N_item").css("display",
                            "none");
                        N_swift = true;
                    }
                });
            // 删除题目
            $(".N_delete").click(function() {
                $(this).parent().parent().parent().remove();
            });
            // 向上移动题目
            $(".N_up").click(function () {
                var thisNode =  $(this).parent().parent().parent();
                var num = thisNode.index();
                var preNode = $(this).parent().parent().parent().prev();
                var lastNode = $(".N_question dl").last();
                thisNode.insertBefore(preNode);
                if(num == "0"){
                    lastNode.after(thisNode);
                }
            });
            // 向下移动题目
            $(".N_down").click(function () {
                var thisNode =  $(this).parent().parent().parent();
                var nestNode = $(this).parent().parent().parent().next();
                nestNode.insertBefore(thisNode);
                var num = thisNode.index();
                var length = $(".N_question dl").length;
                console.log(length);
                var firstNode = $(".N_question dl").first();
                if(num == length - 1){
                    thisNode.insertBefore(firstNode);
                }
            });
            // 全选
            $(".N_allChose").click(function() {
                $(".N_oneChose").prop("checked", $(this).prop("checked"));
            });
            // 单选如果全部选中 则全选被选中
            var oB = document.body;
            $(".N_oneChose").bind("click",oB,function() {
              alert(554)
                var num = 0;
                for (var i = 0; i < $(".N_oneChose").length; i++) {
                    if ($(".N_oneChose").eq(i).prop("checked")) {
                        num++;
                        console.log(num)
                    } else {
                        num = num
                    }
                }
                if (num == $(".N_oneChose").length) {
                    $(".N_allChose").prop("checked", true)
                }
                if ($(this).prop("checked") == false) {
                    $(".N_allChose").prop("checked", false)
                }
            });
            $(".N_setMark").keyup(function() {
                alert("3")
                $(".N_oneChose").each(function () {
                    if($(this).prop("checked")){
                        $(this).siblings(".N_gaibian").children(".N_mark").val($(".N_setMark").val())
                    }
                });
                statistics();
            });
            // 多选题的得分规则(部分对得分) 全选全不选
            // 全选
            $(".partScoreChose").click(function() {
                $(".onePartScoreChose").prop("checked", $(this).prop("checked"));
                // $(".N_parkMark").prop("disabled",$(this).prop("checked"));
                if ($(".onePartScoreChose").prop("checked") == true) {
                    $(".N_setParkMark").css("background", "#fff");
                    $(".N_setParkMark").prop("disabled", false);
                    $(".N_parkMark").css("background", "#fff");
                    $(".N_parkMark").prop("disabled", false);
                } else {
                    $(".N_setParkMark").prop("value", null);
                    $(".N_setParkMark").css("background", "#ddd");
                    $(".N_setParkMark").prop("disabled", true);
                    $(".N_parkMark").prop("value", null);
                    $(".N_parkMark").css("background", "#ddd");
                    $(".N_parkMark").prop("disabled", true)
                }
                /*
                 * $(".N_parkMark").css({ "background":"#ddd", "border":"1px solid
                 * #cccccc" })
                 */

            });
            // 单选如果全部选中 则全选被选中
            $(".onePartScoreChose").click(function() {
                if ($(this).prop("checked") == true) {
                    $(this).next().css("background", "#fff");
                    $(this).next().prop("disabled", false)
                } else {
                    $(this).next().prop("value", null);
                    $(this).next().css("background", "#ddd");
                    $(this).next().prop("disabled", true)
                }
                var num = 0;
                for (var i = 0; i < $(".onePartScoreChose").length; i++) {
                    if ($(".onePartScoreChose").eq(i).prop("checked")) {
                        num++;
                    } else {
                        num = num;
                    }
                }
                if (num == $(".onePartScoreChose").length) {
                    $(".partScoreChose").prop("checked", true);
                    $(".partScoreChose").next().css("background", "#fff");
                    $(".partScoreChose").next().prop("disabled", false)
                }
                if ($(this).prop("checked") == false) {
                    $(".partScoreChose").prop("checked", false);
                    $(".partScoreChose").next().css("background", "#ddd");
                    $(".partScoreChose").next().prop("disabled", true);
                    $(".partScoreChose").next().prop("value", null);
                }
            });
            $(".N_setParkMark").keyup(function() {
                $(".N_parkMark").val($(".N_setParkMark").val());
            });
            $(".N_mark").keyup(function() {
                statistics();
            });

            $(".N_mark").keyup(function() {
                statistics();
            });
            //鼠标滑过事件
            $(".N_question dl").bind("mouseenter",function () {
                $(this).find(".N_time").css({"margin-right":"9px"});
                $(this).find(".N_open").css("display","inline-block");
                $(this).find(".N_gaibian em").css("display","inline-block");
            });
            $(".N_question dl").bind("mouseleave",function () {
                // $(this).find(".N_time").css({"margin-right":"89px","display":"inline-block"});
                $(this).find(".N_open").css("display","none");
                $(this).find(".N_time").css({"margin-right":"89px"});
                $(this).find(".N_gaibian em").css("display","none");
            })
        })
    }
    render(){

        return(
            <div>
                <h2>编辑试卷</h2>
                <form id="edit_message">
                    <fieldset >
                        <legend>基本信息 <span className="openBtn">收起</span></legend>
                        <ul className="content">
                            <li className="pCatalog">
                                <b>*</b><span>目录名称:</span><input className="V_catalog" type="text" />
                                <div>请选择目录</div>
                            </li>
                            <li className="pName">
                                <b>*</b><span>试卷名称:</span><input className="V_examinationName" type="text" />
                                <div>请填写试卷名称</div>
                            </li>
                            <li className="pIntroduce">
                                <b> </b><span>试卷简介:</span><textarea name="" id="" cols="30" rows="3" className="V_resourceDesc" > </textarea>
                                <div></div>
                            </li>
                            <li className="pMark">
                                <b>*</b><span>及格分数:</span><input className="V_passScore" type="text"/>分
                                <div>请设置及格分数</div>
                            </li>
                        </ul>
                    </fieldset>
                </form>
                <form id="edit_count">
                    <fieldset>
                        <legend>题目统计<span className="openBtn">收起</span></legend>
                        <div className="content">
                            <p className="mark_Head"><span>题型</span><span>题数</span><span>该题型总分</span></p>
                            <ul>
                                <li>单选题</li>
                                <li>多选题</li>
                                <li>判断题</li>
                            </ul>
                            <ul className="contentNum">
                                <li className="contentNum0">0</li>
                                <li className="contentNum1">0</li>
                                <li className="contentNum2">0</li>
                            </ul>
                            <ul className="contentMark">
                                <li className="contentMark0">0</li>
                                <li className="contentMark1">0</li>
                                <li className="contentMark2">0</li>
                            </ul>
                            <p className="mark_Foot">总计: <em className="numSum">0</em>题 <em className="markSum">0</em>分</p>
                        </div>
                    </fieldset>
                </form>
                <form id="edit_details">
                    <input  type="text" className="examinationId" name="id" hidden="hidden" value={this.props.exaId}/>
                    <input  type="text" className="examinationName" name="examinationName" hidden="hidden"/>
                    <textarea className="resourceDesc" name="resourceDesc" id="" cols="30" rows="3" hidden="hidden" >13</textarea>
                    <input className="passScore" name="passScore" type="text" hidden="hidden"/>
                    <input className="totalScore" name="totalScore" hidden="true" />
                    <fieldset>
                        <legend>题目详情 <span className="openBtn">收起</span></legend>
                        <div className="N_top">
                            选择题型：
                            <select className="selectType">
                                <option value="4">全部</option>
                                <option value ="0">单选题</option>
                                <option value ="1">多选题</option>
                                <option value="2">判断题</option>
                            </select>
                            <div className="all_mark">
                                <input type="checkbox" className="N_allChose"/>全选&nbsp;&nbsp;&nbsp;
                                设置分数：<input type="text" className="N_setMark"/>分
                                &nbsp;&nbsp;&nbsp;
                                <span className="hiddenPartScore" hidden="true"><input type="checkbox" className="partScoreChose"/>部分对得分
                                            <input type="text" disabled="disabled" className="N_setParkMark" />分</span>
                                <b>新建题目</b>
                                <b className="select_pro" onClick={this.props.selectExam}>从题库选题</b>
                            </div>
                            <div className="N_question content">
                                <div>
                                    还未添加试题哦，请点击右上方添加
                                </div>
                            </div>
                        </div>
                    </fieldset>
                </form>
                <div id="footBtn">
                    <button className="btn_keep">保存</button>
                    <button>预览</button>
                </div>
            </div>
        )
    }
}
export default ExamEdit

